package com.njwb.util;

import java.sql.*;

/**
 * Description: 封装一个数据库工具类
 * Author: yuandeyin@itany.com
 * Date: 2025-08-11 10:11
 * Version: 1.0
 */
public class DBUtil {

    static{
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接  Step2
     * @return
     */
    public static Connection getConnection()throws SQLException{
        //第一个版本先写死，等会再写活
        String url = "jdbc:mysql://localhost:3306/db_test?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT";
        String user = "root";
        String password = "root";
        Connection conn = null;
        conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    /**
     * 关闭资源，专用于 insert 、delete、update操作后关闭资源
     * @param pstmt
     * @param conn
     */
    public static void close(PreparedStatement pstmt,Connection conn){
        if(null != pstmt){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭资源，专用于查询操作后关闭资源
     * @param rs
     * @param pstmt
     * @param conn
     */
    public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn){
        if(null != rs){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(pstmt,conn);
    }
}
